<?php
/**
 * @author renjianhong
 * @date 2021-10-28
 */
namespace Modules\Order\Services\Api;

use App\Models\Area;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Order\Entities\BaseModel;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\Cart;
use Modules\Order\Entities\GoodsCat;
use Modules\Order\Entities\GoodsCats;
use Modules\Order\Entities\Goods;
use Modules\Order\Entities\UserLevel;
use Modules\Order\Entities\User;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\OrderRefund;

use Modules\Order\Entities\ShareSetting;

use function Sodium\compare;

class ShareOrderServices extends BaseService
{
    /**
     * @var Request
     */
    private $request;
    private $share_setting;

    /**
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取分销团队总人数
     * @return
     */
    public function getTeamCount($user_id)
    {
        $share_setting = ShareSetting::first();
        $this->share_setting = $share_setting;
        $team = [
            'f_c' => [],
            's_c' => [],
        ];
        if (!$share_setting || $share_setting->level == 0) {
            return [
                'team_count' => 0,
                'team' => $team
            ];
        }
        if ($share_setting->level == 4) {
            return [
                'team_count' => 0,
                'team' => $team
            ];
        }
        
        $first = User::select('id')
            ->where('parent_id_1' , $user_id)->whereNull('deleted_at')->get()->toArray();
        
        $count = count($first);
        $team['f_c'] = $first;
        if ($share_setting->level >= 2) {
            $second = User::select(['id'])
                ->where('parent_id_1' , $first)->whereNull('deleted_at')->get()->toArray();
            $count += count($second);
            $team['s_c'] = $second;
        }
        return [
            'team_count' => $count,
            'team' => $team
        ];
    }

    /**
     * 获取分销订单详情
     * @return
     */
    public function list()
    {
        $limit = $this->request->input('limit',10);
        $page = $this->request->input('page',1);
        $status = $this->request->input('status',0);
        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $arr = $this->getTeamCount($user_id);
        
        $team_arr = $arr['team'];
        $share_setting = ShareSetting::first();;
        
        if ($share_setting->level == 0) {
            return ;
        }

        //闭包查询条件
        $where = function($q)use($share_setting,$user_id){
			$q->where([
                ['order.is_recycle','=',0],
                ['order.is_delete','=',0],
                ['order.user_id','=',$user_id]
            ]);
            if ($share_setting->level != 4) {

                $q->orWhere('order.user_id','!=',$user_id);

                if ($share_setting->level >= 1) {
                    $q->where('order.parent_id_1','=',$user_id);
                }
                if ($share_setting->level >= 2) {
                    $q->orWhere('order.parent_id_2','=',$user_id);
                }
            }
		};
        /*
        $first = [];
        $second = [];
        foreach($team_arr['f_c'] as $key => $v){
            $first[] = $v['id'];
        }
        foreach($team_arr['s_c'] as $key => $v){
            $second[] = $v['id'];
        }
        if($first){
            $where[] = ['parent_id_1','in',$first];
        }
        if($second){
            $where[] = ['parent_id_2','in',$second];
        }
        */
        
        //求偏移量
        $offset = ($page-1)*$limit;

        $query = Order::where($where)->leftJoin('users', 'users.id','=','order.user_id');

        if ($status == -1) {
        
        } elseif ($status == 0) {
            $query->where([
                ['order.order_status','=',0],
                ['order.is_price','=',0]
            ]);
        } elseif ($status == 1) {
            $query->where([
                ['order.is_price','=',0]
            ]);
            $query->whereIn('order_status', [1,2]);
        } elseif ($status == 2) {
            $query->where([
                ['order.is_price','=',1]
            ]);
            
        }
        $count = $query->count();
        
        $list = $query->select('order.*','users.nickname','users.avatar as avatar_url')
                ->offset($offset)->limit($limit)
                ->GroupBy('order.id')
                ->orderBy('order.created_at','desc')
                ->get()->toArray();
        
        $new_list = [];
        foreach ($list as $index => $value) {
            
            $new_list[$index]['order_no'] = $value['order_no'];
            $new_list[$index]['nickname'] = $value['nickname'];
            $new_list[$index]['avatar_url'] = $value['avatar_url'];
            $new_list[$index]['is_price'] = $value['is_price'];
            if ($value['order_status'] == 0) {
                $new_list[$index]['status'] = "待付款";
            } elseif ($value['order_status'] == 1 || $value['order_status'] == 2) {
                $new_list[$index]['status'] = "已付款";
            } elseif ($value['is_price'] == 1) {
                $new_list[$index]['status'] = "已完成";
            }
            
            if ($value['parent_id_1'] == $user_id) {
                $new_list[$index]['share_status'] = $share_setting->first_name ? $share_setting->first_name : "一级";
                $new_list[$index]['share_money'] = $value['first_price'];
            } elseif ($value['parent_id_2'] == $user_id) {
                $new_list[$index]['share_status'] = $share_setting->second_name ? $share_setting->second_name : "二级";
                $new_list[$index]['share_money'] = $value['second_price'];
            }
            
            if ($value['rebate'] > 0 && $value['user_id'] == $user_id) {
                $new_list[$index]['share_status'] = "自购返现";
                $new_list[$index]['share_money'] = $value['rebate'];
            }


            //订单商品详情
            $new_list[$index]['orderDetail'] = [];
            
            $new_list[$index]['orderDetail'] = $this->getOrderDetail($value['id']);
            $refund = OrderRefund::where([['order_id' ,'=', $value['id']], ['is_delete' ,'=', 0],['refund_type' ,'=', 1]])->first();
            
            if ($refund) {
                if ($refund['status'] == 1) {
                    $new_list[$index]['status'] = "已退款";
                } elseif ($refund['status'] == 0) {
                    $new_list[$index]['status'] = '售后申请中';
                }
            }
        }
        $data = [
            'row_count' => $count,
            'list' => $new_list,
        ];
        return $data;
    }

    /**
     * 订单详情
     * @return $list
     */
    private function getOrderDetail($id)
    {
        $list = OrderDetail::where('order_id', $id)
            ->select('id', 'goods_num as num', 'goods_pic', 'goods_name as name')
            ->get()->toArray();
        
        return $list;
    }

}